<template>
  <el-dialog
    :visible.sync="visible"
    top="30px"
    width="800px"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form :model="data" :rules="rules" ref="form" label-width="140px">
      <el-form-item label="用户名" prop="userName">
        <el-input
          placeholder="用户名"
          class="form-control-ml"
          :disabled="type"
          v-model="data.userName"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" v-if="!type" prop="password">
        <el-input
          type="password"
          placeholder="密码"
          class="form-control-ml"
          v-model="data.password"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" v-if="!type" prop="password2">
        <el-input
          type="password"
          placeholder="再次输入密码"
          class="form-control-ml"
          v-model="data.password2"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <select-dept :clearable="false" class="form-control-ml" v-model="data.deptId"></select-dept>
      </el-form-item>
      <el-form-item label="职务">
        <el-input
          placeholder="职务"
          class="form-control-ml"
          v-model="data.empDescription"
        ></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input placeholder="姓名" class="form-control-ml" v-model="data.realName"></el-input>
      </el-form-item>
      <el-form-item label="联系电话/座机号" prop="phoneNumber">
        <el-input
          placeholder="联系电话/座机号"
          class="form-control-ml"
          v-model="data.phoneNumber"
        ></el-input>
      </el-form-item>
      <el-form-item label="账号权限">
        <select-authority v-model="data.scopes" class="form-control-ml"></select-authority>
      </el-form-item>
      <el-form-item label="所属地">
        <select-address
          v-model="data.addressCode"
          class="form-control-ml"
          auto-top
          placeholder="选择地址"
        ></select-address>
      </el-form-item>
      <el-form-item label="地址详情">
        <el-input
          placeholder="地址详情"
          class="form-control-ml"
          v-model="data.addressDetail"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="btn-long" @click="onSubmit" :loading="loading">
          保 存
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUser, putUser, createUser } from '@/common/api/auth'

import SelectDept from '@/components/select/SelectDept'
import SelectAddress from '@/components/select/SelectAddress'
import { phoneValidator } from '@/common/plugins/validator'
import SelectAuthority from '@/gov/components/select/SelectAuthority'
export default {
  components: {
    SelectAddress,
    SelectDept,
    SelectAuthority,
  },

  props: {
    visible: Boolean,
    userData: Object,
    userId: String,
  },

  data() {
    let validateName = (rule, value, callback) => {
      if (!/^[0-9a-zA-Z\-_]*$/g.test(value)) {
        callback(new Error('用户名只能由英文、数字、下划线组成'))
      } else {
        callback()
      }
    }
    let validatePass = (rule, value, callback) => {
      if (value !== this.data.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      data: {
        userName: '',
        deptId: '',
        realName: '',
        addressCode: '',
        addressDetail: '',
        nickName: '',
        phoneNumber: '',
        password: '',
        remark: '',
        password2: '',
        scopes: [],
      },
      initData: {},
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' },
        ],
        realName: [{ required: true, message: '请输入政府单位名', trigger: 'blur' }],
        // addressCode: [{ required: true, message: '请选择地址', trigger: 'blur' }],
        nickName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        phoneNumber: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: phoneValidator, trigger: 'blur' },
        ],
        deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        password2: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' },
        ],
      },
      loading: false,
      clientId: '',
    }
  },

  computed: {
    ...mapGetters(['user']),
    id() {
      return this.userId || this.userData ? this.userData.userId : ''
    },
    type() {
      return !!this.id
    },
  },

  watch: {
    userId() {
      this.getData()
    },
    userData: {
      handler: function () {
        this.getData()
      },
      deep: true,
    },
  },

  created() {
    this.data.addressCode = this.user.addressCode || this.$utils.getAddressCode()
    this.initData = { ...this.data }
    this.clientId = this.$utils.getClientId()
    this.getData()
  },

  mounted() {},

  methods: {
    getData() {
      if (this.userData) {
        this.initForm(this.userData)
      } else if (this.userId) {
        this.loading = true
        getUser({
          userId: this.userId,
          clientId: this.clientId,
        })
          .then(res => {
            this.initForm(res.data)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },

    initForm(data) {
      this.data = { ...data }
      this.data.scopes = data.scopes.split('|')
    },

    beforeClose() {
      this.data = { ...this.initData }
      this.$refs.form.clearValidate()
      this.$emit('update:visible', false)
    },

    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.type) {
            this.putUser()
          } else {
            this.postUser()
          }
        } else {
          this.$message.warning('输入错误，请重新输入！')
        }
      })
    },

    putUser() {
      this.loading = true
      putUser({
        realName: this.data.realName,
        nickName: this.data.nickName,
        phoneNumber: this.data.phoneNumber,
        deptId: this.data.deptId,
        addressCode: this.data.addressCode,
        addressDetail: this.data.addressDetail,
        clientId: this.clientId,
        userId: this.id,
        empDescription: this.data.empDescription,
        scopes: this.data.scopes.join('|'),
      })
        .then(() => {
          this.actionSuccess()
          if (this.id === this.user.userId) {
            this.$store.dispatch('getMe').then(res => {
              this.$store.dispatch('generateRoutes', res)
            })
          }
        })
        .catch(() => {
          this.$message.error('修改账号失败，请重试！')
        })
        .then(() => {
          this.loading = false
        })
    },

    postUser() {
      let data = {
        userName: this.data.userName,
        password: this.data.password,
        realName: this.data.realName,
        nickName: this.data.nickName,
        phoneNumber: this.data.phoneNumber,
        remark: this.data.remark,
        clientId: this.clientId,
        deptId: this.data.deptId,
        addressCode: this.data.addressCode,
        addressDetail: this.data.addressDetail,
        empDescription: this.data.empDescription,
        scopes: this.data.scopes.join('|'),
      }
      this.loading = true
      createUser(data)
        .then(() => {
          this.actionSuccess()
        })
        .catch(err => {
          this.$message.error(err?.data?.errorDescription ?? '添加账号失败，请重试！')
        })
        .then(() => {
          this.loading = false
        })
    },

    actionSuccess() {
      this.$message.success(`${this.type ? '修改' : '添加'}成功！`)
      this.$emit('success', true)
      this.beforeClose()
    },
  },
}
</script>

<style scoped>
.form-sl {
  width: 197px;
}
</style>
